package com.panopset.sf;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import com.panopset.sf.env.Screener;

/**
 * Text display frame.
 * 
 * @author Karl Dinwiddie
 * 
 */
public class TextFrame {

	public TextFrame(final Image icon16x16, String title) {
		i = icon16x16;
		t = title;
	}

	private JPanel getPanel() {
		if (p == null) {
			p = new JPanel(new BorderLayout());
			p.add(BorderLayout.CENTER, new JScrollPane(getMsgTA()));
			p.add(BorderLayout.SOUTH, getOkBtn());
		}
		return p;
	}

	public void show(final String msg) {
		getMsgTA().setText(msg);
		getFrame().setVisible(true);
	}

	private JButton okBtn;
	
	private JButton getOkBtn() {
		if (okBtn == null) {
			okBtn = new JButton("OK");
			okBtn.setMnemonic(KeyEvent.VK_O);
			okBtn.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					getFrame().dispose();
				}
				
			});
			okBtn.requestFocus();
		}
		return okBtn;
	}
	private JTextArea msgTA;

	private JTextArea getMsgTA() {
		if (msgTA == null) {
			msgTA = new JTextArea();
			FontManager.getInstance().register(msgTA,
					FontManager.FontType.monospace);
			msgTA.setEditable(false);
		}
		return msgTA;
	}

	/**
	 * Frame.
	 */
	private JFrame frame;

	/**
	 * @return Dialog frame.
	 */
	public JFrame getFrame() {
		if (frame == null) {
			frame = new JFrame();
			frame.setTitle(t);
			frame.setSize(DIALOG_DIMENSIONS);
			frame.setLocation(new Screener().centerInScreen(DIALOG_DIMENSIONS));
			frame.setIconImage(i);
			frame.add(getPanel());
            frame.getRootPane().setDefaultButton(getOkBtn());
			frame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		}
		return frame;
	}

	/**
	 * Dialog width.
	 */
	public static final int DEFAULT_DIALOG_WIDTH = 600;

	/**
	 * Dialog height.
	 */
	public static final int DEFAULT_DIALOG_HEIGHT = 300;

	/**
	 * Dialog dimensions are 600, 300.
	 */
	public static Dimension DIALOG_DIMENSIONS = new Dimension(
			DEFAULT_DIALOG_WIDTH, DEFAULT_DIALOG_HEIGHT);

	private final Image i;
	private final String t;
	private JPanel p;
}
